<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue';

import { useRouter } from 'vue-router';
import axios from '@/utils/axios';

// 接收父组件传递的关键词
const props = defineProps<{
  keyword: string;
}>();
// 获取路由实例
const router = useRouter();

// 跳转到商品详情页面
const goToProductDetail = (productId: number) => {
  router.push({name:'shopdetail',params:{id:productId}});
};

// 商品列表数据
const products = ref([]);
// 每页加载数量
const pageSize = 8;
// 当前页码
const currentPage = ref(1);
// 是否正在加载
const loading = ref(false);
// 是否还有更多数据
const hasMore = ref(true);
// 容器引用
const containerRef = ref<HTMLElement | null>(null);
// 是否显示底部提示
const showBottomTip = ref(false);
// 底部提示定时器
let bottomTipTimer: number | null = null;

// 幽默提示语列表
const funnyMessages = [
  "我们是有底线的，这里就是底线~",
  "别拉了，真的没有了~",
  "客官，菜(商品)已上完，请慢用!",
  "更多好物正在路上，稍等片刻~",
  "我是有极限的，这里是极限了~",
  "老板说到底了，让我去休息会儿~",
  "别点了，再点就出bug了~",
  "我们是正经的水果店，不是无底洞~"
];

// 获取随机幽默提示语
const getRandomFunnyMessage = () => {
  const randomIndex = Math.floor(Math.random() * funnyMessages.length);
  return funnyMessages[randomIndex];
};

// 计算两列布局的商品列表
const twoColumnProducts = computed(() => {
  // 创建一个二维数组，分别代表左右两列
  const columns = [[], []];

  // 将商品按顺序分配到两列中
  products.value.forEach((product, index) => {
    columns[index % 2].push(product);
  });

  return {
    left: columns[0],
    right: columns[1]
  };
});

// 显示底部提示
const showBottomNotification = () => {
  // 如果已经在显示或者还有更多数据，就不显示提示
  if (showBottomTip.value || hasMore.value) return;

  showBottomTip.value = true;

  // 2秒后自动隐藏
  if (bottomTipTimer) {
    clearTimeout(bottomTipTimer);
  }

  bottomTipTimer = window.setTimeout(() => {
    showBottomTip.value = false;
    bottomTipTimer = null;
  }, 2000);
};

// 从后端加载商品数据
const loadProducts = async () => {
  if (loading.value || !hasMore.value) return;

  loading.value = true;

  try {
    // 发起分页请求，每次请求8条数据
    const response = await axios.get('/api/goods/getByKeyword', {
      params: {
        page: currentPage.value,
        size: pageSize,
        // 搜索关键词
        keyword: props.keyword
      }
    });

    // 假设后端返回的数据结构为 { data: [...], total: number }
    const newProducts = response.data.records || [];

    if (newProducts.length > 0) {
      products.value = [...products.value, ...newProducts];
      currentPage.value++;
    }

    // 如果返回的数据少于pageSize，说明已经没有更多数据了
    if (newProducts.length < pageSize) {
      hasMore.value = false;
    }
  } catch (error) {
    console.error('加载商品数据失败:', error);
    // 出错时也停止加载，避免无限重试
    hasMore.value = false;
  } finally {
    loading.value = false;
  }
};

// 滚动处理函数
const handleScroll = () => {
  if (!containerRef.value) return;

  const container = containerRef.value;
  const scrollTop = container.scrollTop;
  const clientHeight = container.clientHeight;
  const scrollHeight = container.scrollHeight;

  // 当滚动到底部附近时加载更多
  if (scrollHeight - scrollTop - clientHeight < 100) {
    loadProducts();
  }
  // 当滚动到底部并且没有更多数据时显示提示
  else if (scrollHeight <= scrollTop + clientHeight && !hasMore.value) {
    showBottomNotification();
  }
};

// 组件挂载时初始化数据和事件监听
onMounted(() => {
  loadProducts(); // 初始加载第一页数据
  if (containerRef.value) {
    containerRef.value.addEventListener('scroll', handleScroll);
  }
});

// 组件卸载时移除事件监听和清理定时器
onUnmounted(() => {
  if (containerRef.value) {
    containerRef.value.removeEventListener('scroll', handleScroll);
  }

  if (bottomTipTimer) {
    clearTimeout(bottomTipTimer);
  }
});
</script>





<template>
  <div v-if="products.length === 0" class="no-products">
    暂无该商品
  </div>
  <div class="shop-container" ref="containerRef" v-else>
    <!-- 商品列表 -->
    <div class="products-container">
      <!-- 使用两列布局 -->
      <div class="two-column-layout">
        <div class="column left-column">
          <div
              v-for="product in twoColumnProducts.left"
              :key="product.goodId"
              class="product-card"
              @click="goToProductDetail(product.goodId)"
          >
            <div class="product-image-container">
              <img :src="product.smallimg" class="product-image" />
            </div>
            <!-- 修改商品信息部分 -->
            <div class="product-info">
              <div class="product-name">{{ product.name }}</div>
              <div class="product-price-container">
                <span class="product-price">¥{{ product.price }}</span>
                <span class="product-original-price">¥{{ product.oriPrice }}</span>
              </div>
              <div class="product-sales-info">
                <span class="product-sales">销量{{ product.sales }}</span>
                <span class="product-views">浏览{{ product.views || 0 }}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="column right-column">
          <div
              v-for="product in twoColumnProducts.right"
              :key="product.goodId"
              class="product-card"
              @click="goToProductDetail(product.goodId)"
          >
            <div class="product-image-container">
              <img :src="product.smallimg" class="product-image" />
            </div>
            <!-- 修改商品信息部分 -->
            <div class="product-info">
              <div class="product-name">{{ product.name }}</div>
              <div class="product-price-container">
                <span class="product-price">¥{{ product.price }}</span>
                <span class="product-original-price">¥{{ product.oriPrice }}</span>
              </div>
              <div class="product-sales-info">
                <span class="product-sales">销量{{ product.sales }}</span>
                <span class="product-views">浏览{{ product.views || 0 }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载提示 -->
      <div class="loading-container" v-if="loading">
        <van-loading size="24px" vertical>加载中...</van-loading>
      </div>

      <!-- 没有更多数据提示 -->
      <div class="no-more-container" v-if="!hasMore && products.length > 0">
        <div class="funny-message">{{ getRandomFunnyMessage() }}</div>
      </div>
    </div>

    <!-- 底部提示 -->
    <div
        class="bottom-tip"
        :class="{ hide: !showBottomTip }"
        v-if="showBottomTip"
    >
      {{ getRandomFunnyMessage() }}
    </div>
  </div>

</template>




<style scoped>
.shop-container {
  background: linear-gradient(135deg, #F5FFFA, #F0FFF0);
  min-height: 100vh;
  padding-bottom: 20px;
  height: calc(100vh - 50px); /* 减去底部导航栏高度 */
  overflow-y: auto;
  position: relative;
}

.tab-container {
  display: flex;
  position: relative;
  background: white;
  border-radius: 0 0 20px 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 15px;
  position: sticky;
  top: 0;
  z-index: 100;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 15px 0;
  font-size: 16px;
  font-weight: 500;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 1;
}

.tab-item.active {
  color: #32CD32;
  font-weight: 600;
}

.tab-indicator {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 50%;
  height: 3px;
  background: #32CD32;
  transition: transform 0.3s ease;
}

.tab-indicator.category {
  transform: translateX(100%);
}

.swipe-wrapper {
  position: relative;
  margin-bottom: 20px;
}

.swipe-container {
  height: 200px;
}

.swipe-item-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.swipe-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.swipe-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom, rgba(0,0,0,0.1), rgba(0,0,0,0.3));
}

.swipe-title {
  position: absolute;
  top: 20px;
  left: 20px;
  color: white;
  font-size: 20px;
  font-weight: bold;
  text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
  z-index: 10;
}

.products-container {
  padding: 0 15px;
  width: 100%;
  box-sizing: border-box;
}

/* 两列布局 */
.two-column-layout {
  display: flex;
  gap: 15px;
  width: 100%;
}

.column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 15px;
  width: 0; /* 防止列宽溢出 */
  /* 移除 align-items: stretch 以避免强制对齐 */
}

.product-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.1);
  break-inside: avoid;
  overflow: hidden;
  transition: all 0.3s ease;
  border: 1px solid rgba(50, 205, 50, 0.1);
  cursor: pointer;
  margin-bottom: 0;
  /* 移除 flex: 1 1 auto 以避免强制拉伸 */
  display: flex;
  flex-direction: column;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
  border-color: rgba(50, 205, 50, 0.3);
}

.product-image-container {
  width: 100%;
  overflow: hidden;
  /* 移除 flex: 1 以避免强制填充 */
}

.product-image {
  width: 100%;
  height: auto;
  transition: transform 0.3s ease;
  display: block;
  object-fit: cover;
}

.product-card:hover .product-image {
  transform: scale(1.03);
}

.product-info {
  padding: 15px;
}

.product-name {
  font-size: 15px;
  font-weight: 500;
  color: #333;
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  min-height: 54px;
}

.product-price-container {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
}

.product-price {
  font-size: 20px;
  font-weight: bold;
  color: #32CD32;
  margin-right: 8px;
}

.product-original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.product-sales {
  font-size: 13px;
  color: #999;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  width: 100%;
}

.no-more-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30px 20px;
  color: #999;
  font-size: 14px;
  text-align: center;
  width: 100%;
}

.funny-message {
  padding: 15px 25px;
  background: rgba(50, 205, 50, 0.1);
  border-radius: 20px;
  font-style: italic;
  color: #666;
  border: 1px dashed #32CD32;
}

/* 底部提示样式 */
.bottom-tip {
  position: fixed;
  bottom: 70px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(50, 205, 50, 0.9);
  color: white;
  padding: 12px 24px;
  border-radius: 30px;
  font-size: 14px;
  z-index: 1000;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
}

.bottom-tip.hide {
  opacity: 0;
  transform: translate(-50%, 20px);
}

:deep(.van-swipe__indicator) {
  background-color: rgba(255, 215, 0, 0.5);
  width: 20px;
  height: 3px;
  border-radius: 2px;
}

:deep(.van-swipe__indicator--active) {
  background-color: #FFD700;
  width: 25px;
}

@media (max-width: 768px) {
  .product-card {
    border-radius: 12px;
  }

  .product-info {
    padding: 12px;
  }

  .product-name {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin-bottom: 10px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    line-height: 1.4;
    font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
    letter-spacing: 0.5px;
  }

  .product-price {
    font-size: 18px;
  }
}
.no-products {
  text-align: center;
  padding: 30px;
  color: #999;
}
/* 商品销售信息容器 */
.product-sales-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

/* 销量信息 */
.product-sales {
  font-size: 13px;
  color: #ff6600;
  font-weight: 500;
}

/* 浏览量信息 */
.product-views {
  font-size: 12px;
  color: #666;
  background-color: #f5f5f5;
  padding: 2px 8px;
  border-radius: 12px;
}
</style>







